<?php

include 'config.php';
include 'common.php';


if (!isset($_COOKIE['token'])) {
    //微信内
    $code = $_GET['code'];
    $data = array(
        "appid" => $config['AppId'],
        "secret" => $config['AppSecret'],
        "code" => $code,
        "grant_type" => "authorization_code"
    );
    $url = "https://api.weixin.qq.com/sns/oauth2/access_token";
    $json = curlRequest($url, false, $data);
    $json = json_decode($json);
    $info_data = array(
        "access_token" => $json->access_token,
        "openid"       => $json->openid,
        "lang"         => "zh_CN"
    );
    $info = curlRequest("https://api.weixin.qq.com/sns/userinfo", false, $info_data);
    $data = json_decode($info,true);
    //调取注册接口
    $post = array();
    $post['openid'] = $data['openid'];
    $payload = array(
        'openid' => $data['openid'],
        'city' => $data['city'],
        'country' => $data['country'],
        'province' => $data['province'],
        'sex' => $data['sex'],
        'headimgurl' => $data['headimgurl'],
        'nickname' => $data['nickname'],
        'unionid' => $data['unionid'],
    );
    $post['type'] = "wechat";

    if((!empty($_COOKIE['recommend'])) && is_numeric($_COOKIE['recommend'])) {
        $payload['recommend'] = intval($_COOKIE['recommend']);
    }
    if((!empty($_COOKIE['masterid'])) && is_numeric($_COOKIE['masterid'])) {
        $payload['masterid'] = intval($_COOKIE['masterid']);
    }
    $post['payload'] = json_encode($payload);
    $result = curlRequest($config['LoginApi'],true,$post);
    $result = json_decode($result,true);
    if($result['code'] == 0) {
        $time = time();
        setcookie("openid",$json->openid,$time + 3600*24*30);
        setcookie("token",$result['data']['token'], $time + 3600*24*30 );
        setcookie("nickname",urlencode($result['data']['nickname']), $time + 3600*24*30 );
        setcookie("avatar",$result['data']['avatar'], $time + 3600*24*30 );
        setcookie("coinbalance",$result['data']['coinbalance'], $time + 3600*24*30 );
        setcookie("uid",$result['data']['uid'], $time + 3600*24*30);

        if(!isset($_COOKIE['url'])) {
            header("Location: https://m.mxzhuawawa.com/");
        } else {
            $url = $_COOKIE['url'];
            header("Location: {$url}");
        }
    }
} else {
    header("Location: https://m.mxzhuawawa.com/");
}

